package types

import (
	"bytes"
	"fmt"
)

type Record struct {
	fieldRefs []interface{}
	fields    []Field
}

func NewRecord(fieldDescList []FieldDesc) (*Record, error) {
	fields, err := NewFields(fieldDescList)
	if err != nil {
		return nil, err
	}
	fieldRefs := make([]interface{}, 0, len(fields))
	for _, field := range fields {
		fieldRefs = append(fieldRefs, field.Ref())
	}
	return &Record{
		fieldRefs: fieldRefs,
		fields:    fields,
	}, nil
}

func (r *Record) FieldRefs() []interface{} {
	return r.fieldRefs
}

func (r *Record) Print() {
	for _, field := range r.fields {
		fmt.Printf("%s ", field.AsString())
	}
	fmt.Println()
}

func (r *Record) Bytes() []byte {
	buffer := bytes.NewBuffer(nil)
	for _, field := range r.fields {
		buffer.Write(field.Bytes())
	}
	return buffer.Bytes()
}

func (r *Record) Count() int {
	return len(r.fieldRefs)
}

func (r *Record) ByteList() [][]byte {
	list := make([][]byte, 0, len(r.fieldRefs))
	for _, field := range r.fields {
		list = append(list, field.Bytes())
	}
	return list
}
